<template>
  <div class="user-add">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>添加用户</span>
          <el-button @click="$router.go(-1)">返回</el-button>
        </div>
      </template>
      
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-width="120px" 
        class="user-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input 
                v-model="form.username" 
                placeholder="请输入用户名"
                maxlength="20"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="realName">
              <el-input 
                v-model="form.realName" 
                placeholder="请输入真实姓名"
                maxlength="20"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input 
                v-model="form.password" 
                type="password" 
                placeholder="请输入密码"
                show-password
                maxlength="20"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input 
                v-model="form.confirmPassword" 
                type="password" 
                placeholder="请再次输入密码"
                show-password
                maxlength="20"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input 
                v-model="form.email" 
                placeholder="请输入邮箱地址"
                type="email"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input 
                v-model="form.phone" 
                placeholder="请输入手机号"
                maxlength="11"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属部门" prop="department">
              <el-select v-model="form.department" placeholder="请选择部门">
                <el-option label="技术部" value="技术部"></el-option>
                <el-option label="人事部" value="人事部"></el-option>
                <el-option label="财务部" value="财务部"></el-option>
                <el-option label="行政部" value="行政部"></el-option>
                <el-option label="市场部" value="市场部"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职位" prop="position">
              <el-input 
                v-model="form.position" 
                placeholder="请输入职位"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户角色" prop="roles">
              <el-select 
                v-model="form.roles" 
                multiple 
                placeholder="请选择角色"
                style="width: 100%"
                filterable
              >
                <el-option 
                  v-for="role in roleOptions" 
                  :key="role.value" 
                  :label="role.label" 
                  :value="role.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="账号状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio label="active">启用</el-radio>
                <el-radio label="inactive">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入职日期" prop="hireDate">
              <el-date-picker
                v-model="form.hireDate"
                type="date"
                placeholder="选择入职日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工号" prop="employeeId">
              <el-input 
                v-model="form.employeeId" 
                placeholder="请输入工号"
                maxlength="20"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="备注">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" :loading="submitting">
            提交
          </el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="$router.go(-1)">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { userApi, roleApi } from '@/api'

const router = useRouter()
const route = useRoute()
const formRef = ref<FormInstance>()
const submitting = ref(false)
const isEdit = ref(false)
const userId = ref<number | null>(null)

// 表单数据
const form = reactive({
  username: '',
  realName: '',
  password: '',
  confirmPassword: '',
  email: '',
  phone: '',
  department: '',
  position: '',
  roles: [],
  status: 'active',
  hireDate: '',
  employeeId: '',
  remark: ''
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
    { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/, message: '密码必须包含大小写字母和数字', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value !== form.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  department: [
    { required: true, message: '请选择所属部门', trigger: 'change' }
  ],
  position: [
    { required: true, message: '请输入职位', trigger: 'blur' }
  ],
  roles: [
    { required: true, message: '请选择用户角色', trigger: 'change' },
    { type: 'array', min: 1, message: '至少选择一个角色', trigger: 'change' }
  ],
  hireDate: [
    { required: true, message: '请选择入职日期', trigger: 'change' }
  ],
  employeeId: [
    { required: true, message: '请输入工号', trigger: 'blur' }
  ]
}

// 角色下拉选项
const roleOptions = ref<any[]>([])

const loadRoles = async () => {
  const list: any = await roleApi.getAll()
  roleOptions.value = (list || []).map((r: any) => ({ label: r.name, value: Number(r.id) }))
}

// 加载用户数据
const loadUserData = async (id: number) => {
  try {
    const userData = await userApi.getDetail(id)
    if (userData) {
      // 删除密码相关字段
      const { password, confirmPassword, ...userInfo } = userData
      
      // 转换状态为前端格式
      const status = userInfo.status === 1 ? 'active' : 'inactive'
      
      // 转换角色为前端使用的格式
      const roles = userInfo.roleIds || (userInfo.roles?.map((r: any) => r.id || r.code) || [])
      
      Object.assign(form, { 
        ...userInfo, 
        status,
        roles,
        password: '',
        confirmPassword: ''
      })
    }
  } catch (error) {
    console.error('加载用户数据失败:', error)
    ElMessage.error('加载用户数据失败')
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    // 确保角色ID是数字类型
    const roleIds = form.roles.map((roleId: any) => {
      // 如果是字符串但可以转换为数字，则进行转换
      if (typeof roleId === 'string' && !isNaN(Number(roleId))) {
        return Number(roleId)
      }
      return roleId
    })
    
    const payload: any = {
      ...form,
      fullName: form.realName,
      roleIds,
      status: form.status === 'active' ? 1 : 0
    }
    delete payload.realName;
    delete payload.roles;

    if (isEdit.value && userId.value) {
      await userApi.update(userId.value, payload)
      ElMessage.success('用户更新成功')
    } else {
      await userApi.add(payload)
      ElMessage.success('用户添加成功')
    }
    router.push('/user/list')
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
}

onMounted(() => {
  loadRoles()
  
  // 检查是否为编辑模式
  const id = route.params.id
  if (id) {
    isEdit.value = true
    userId.value = Number(id)
    loadUserData(Number(id))
  }
})
</script>

<style scoped>
.user-add {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-form {
  max-width: 800px;
  margin: 0 auto;
}

@media (max-width: 768px) {
  .user-add {
    padding: 10px;
  }
  
  .user-form {
    max-width: 100%;
  }
}
</style> 